package com.webserver.http;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  用来定义所有HTTP协议中会被重用的内容
 */
public class HttpContext {
    /**
     *  保存所有的资源后缀名与响应头Content-Type的对应关系
     *  key:资源后缀名
     *  value:Content-Type对应值
     */
    private static Map<String,String> mimeMapping = new HashMap<>();

    static {
        initMimeMapping();
    }

    private static void initMimeMapping(){
        try {
            SAXReader reader = new SAXReader();
            Document doc = reader.read("./config/web.xml");
            Element root = doc.getRootElement();

            List<Element> list = root.elements("mime-mapping");
            for (Element ele : list){
                String k = ele.elementText("extension");
                String v = ele.elementText("mime-type");
                mimeMapping.put(k,v);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据后缀获取对应的Content-Type的值
     * @param ext
     * @return
     */
    public static String getMimeType(String ext){
        return mimeMapping.get(ext);
    }


}